from nicegui import app, ui, native, run
from tools import qiuziti, quzuotu
import pandas as pd
import functools


def get_father_div():
    return ui.element("div").classes("container mx-auto flex flex-row flex-wrap p-1 text-base")


@ui.page('/')
def index_page():
    card_class = "h-full"
    div_class = "p-2 basis-1/4"

    with get_father_div():
        card_data_list = [
            {
                "img": "imgs/趣作图.png",
                "title": "百万设计师的选择",
                "desc": "背景图片消除 100%全自动且免费",
                "page": "quzuotu"
            },
            {
                "img": "imgs/求字体.png",
                "title": "求字体当然不求人",
                "desc": "免费字体下载",
                "page": "qiuziti"
            }
        ]
        for one in card_data_list:
            with ui.element("div").classes(div_class):
                with ui.card().classes(card_class):
                    ui.image(one["img"])
                    ui.separator()
                    with ui.card_section().classes("mt-auto mb-0"):
                        ui.label(one["title"]).classes("leading-loose subpixel-antialiased text-2xl font-semibold")
                        ui.label(one["desc"]).classes("leading-loose subpixel-antialiased text-base italic")
                    ui.button('进入使用',
                              on_click=functools.partial(ui.open, one["page"], new_tab=True)
                              ).classes('place-self-end')


@ui.page("/quzuotu")
def quzuotu_page():
    img_list = []

    @ui.refreshable
    def img_gallery_ui() -> None:
        with ui.element("div").classes("p-2 basis-1/5"):
            for img in img_list:
                if isinstance(img, str):
                    ui.image(img)
                else:
                    ui.label(img[-1])
            print(f"{img_list = }")

    async def _process_upload(event):
        name = event.name
        file = event.content
        ok, res = await run.io_bound(quzuotu.remove_bg, file)
        if ok:
            img_list.append(res["result"])
        else:
            img_list.append((1, f"{name}上传失败， {res}"))
        img_gallery_ui.refresh()

    with get_father_div():
        with ui.element("div").classes("w-full flex justify-center items-center"):
            ui.upload(on_upload=_process_upload, multiple=True, auto_upload=False). \
                classes('w-1/2')

        # with ui.element("div").classes("p-2 basis-1/5"):
        img_gallery_ui()


@ui.page("/qiuziti")
def qiuziti_page():
    with get_father_div():
        # ok, data = qiuziti.search_by_name("字体传奇特战体内测版", fetch_size=1000)
        ok, data = qiuziti.search_by_name("字体传奇特战体内测版", fetch_size=1000)
        if not ok:
            ui.label("页面错误。。。")
            return
        item_list = data["list"]
        item_count = data["total"]

        font_df = pd.DataFrame(item_list)
        show_df = font_df[["id", "family", "char_size", "file_size", "file_type", "language"]]

        df = pd.DataFrame(item_list)
        ui.table.from_pandas(df, pagination={'rowsPerPage': 15}).classes('w-full')


ui.run(
    host="localhost",
    title="猪猪工具箱",
    binding_refresh_interval=0.5,
    # native=True,
    favicon="imgs/派大星.ico",
    # frameless=True,
    # port=native.find_open_port()
)
